<?php
/**
 * 更新各类业务表中的FBA库存
 */

namespace App\Logic\SsBasic;

use App\Models\Amazon\FbaFulfillmentInventory;
use App\Models\SalesReport\FBAInventory;
use App\Models\Basics\SysICountry;
use App\Models\Delivery\FBADeliveryDetail;
use App\Models\SsBasic\AreaSkuStock;
use App\Models\Stocking\StockingSku;
use Illuminate\Support\Facades\DB;

class InitFBAStock
{
    /**
     * ss:fab-stock
     * 更新备货提货表中的FBA库存
     *
     * 运行时机：FBA库存报表,FBA收货报表有更新后
     * 设定：自定义运行（每天）
     */
    public static function exe(){
        try{
            $country = [];
            //备货sku
            StockingSku::query()
                ->orderBy('id')
                ->chunk(500, function ($ss) use (&$country){
                    DB::beginTransaction();
                    foreach ($ss as $_ss){
                        if(!array_key_exists($_ss->area_id,$country)){
                            $country[$_ss->area_id] = SysICountry::getCountryIdsByAreaId($_ss->area_id);
                        }
                        $countryIds = $country[$_ss->area_id];

                        //erp-fba库存
                        $inventory = FBAInventory::_getInventory($countryIds,$_ss->psku_id);
                        if($inventory){
                            $instant = $inventory->quantity ?: 0;
                            $transit = $inventory->inbound ?: 0;
                        }else{
                            $instant = 0;
                            $transit = 0;
                        }

                        //备货sku库存
                        $_ss->fba_instant_num = $instant;
                        $_ss->fba_transit_num = $transit;
                        $_ss->save();
                        $_ss->over_stock = StockingSku::getOverStock($_ss);
                        $_ss->over_stock_value = StockingSku::getOverStockValue($_ss->over_stock,$_ss->unit_price);
                        $_ss->save();

                        //备货站点sku库存（FBA）
                        $stock = AreaSkuStock::query()->firstOrNew(['area_psku' => $_ss->area_psku]);
                        $stock->fba_instant_num = $instant;
                        $stock->fba_transit_num = $transit;
                        $stock->save();
                    }
                    DB::commit();
                });
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

    /**
     * ss:fab-re-num
     * 依据Amazon已收货库存报告,更新erp下的FBA发货单(ss:fab-re-num)
     *
     * 同步发货单已收货数量 (每半月)
     */
    public static function receivedNum(){
        try{
            //Amazon-FBA已收货库存
            $fis = FbaFulfillmentInventory::query()
                ->select(DB::raw('fba_shipment_id,seller_sku,sum(quantity) as quantity'))
                ->groupBy(['fba_shipment_id','seller_sku'])
                ->get();
            foreach($fis as $fi){
                $dd = FBADeliveryDetail::query()
                    ->where('delivery_no',$fi->fba_shipment_id)
                    ->where('seller_sku',$fi->seller_sku)
                    ->first();
                if($dd){
                    //FBA发货明细(国内仓发往FBA仓)
                    $dd->received_num = $fi->quantity;
                    $dd->save();

                }else{
                    //FBA发货明细
                    $odd = FBADeliveryDetail::query()
                        ->where('delivery_no',$fi->fba_shipment_id)
                        ->where('seller_sku',$fi->seller_sku)
                        ->first();
                    if(!$odd)continue;
                    $odd->received_num = $fi->quantity;
                    $odd->save();
                }
            }
        }catch (\Exception $e){
            report($e);
        }
    }

    /**
     * ss:fab-re-date
     * 同步发货单首次到货日期 (每半月一次)(ss:fab-re-date)
     */
    public static function receivedDate(){
        try{
            ini_set('memory_limit', '200M');
            set_time_limit(0);

            //Amazon-FBA已收货库存
            $fis = FbaFulfillmentInventory::query()
                ->select('fba_shipment_id','seller_sku')
                ->distinct()
                ->get();
            foreach ($fis as $fi){
                $_fis = FbaFulfillmentInventory::query()
                    ->where('fba_shipment_id',$fi->fba_shipment_id)
                    ->where('seller_sku',$fi->seller_sku)
                    ->orderBy('received_date','ASC')
                    ->first();
                //FBA发货单明细（国内发FBA）
                $dd = FBADeliveryDetail::query()
                    ->where('delivery_no',$fi->fba_shipment_id)
                    ->where('seller_sku',$fi->seller_sku)
                    ->first();
                if($dd){
                    $dd->received_date = $_fis->received_date ?? null;
                    $dd->save();
                }else{
                    //FBA发货单明细
                    $odd = FBADeliveryDetail::query()
                        ->where('delivery_no',$fi->fba_shipment_id)
                        ->where('seller_sku',$fi->seller_sku)
                        ->first();
                    if(!$odd)continue;
                    $odd->received_date = $_fis->received_date ?? null;
                    $odd->save();
                }
            }
        }catch (\Exception $e){
            report($e);
        }
    }

}
